package dev.blogmoon.cn.admin.controller;


import cn.dev33.satoken.stp.StpUtil;
import dev.blogmoon.cn.common.entity.Result;
import dev.blogmoon.cn.common.enums.ErrorCode;
import dev.blogmoon.cn.common.exception.BizException;
import dev.blogmoon.cn.system.module.BizAccountDTO;
import dev.blogmoon.cn.system.module.QueryBizAccountReq;
import dev.blogmoon.cn.system.repository.BizAccountRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import dev.blogmoon.cn.admin.module.req.LoginReq;

import java.util.Objects;

@RequestMapping("/api/v1/admin/login")
@RestController
public class LoginController {

    @Autowired
    private BizAccountRepository bizAccountRepository;

    @PostMapping
    public Result login(@RequestBody LoginReq req) {
        if (Objects.isNull(req.getMobile()) || Objects.isNull(req.getPassword())) {
            throw new BizException(ErrorCode.PARAM_ERROR.getCode(), "用户名或密码不能为空");
        }
        QueryBizAccountReq queryBizAccountReq = new QueryBizAccountReq();
        queryBizAccountReq.setMobile(req.getMobile());
        BizAccountDTO bizAccountDTO = bizAccountRepository.getAccount(queryBizAccountReq);
        if (Objects.isNull(bizAccountDTO)) {
            throw new BizException(ErrorCode.LOGIN_ERROR.getCode(), "用户名或密码错误");
        }
        PasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
        if (!passwordEncoder.matches(req.getPassword(), bizAccountDTO.getPassword())) {
            throw new BizException(ErrorCode.LOGIN_ERROR.getCode(), "用户名或密码错误");
        }
        StpUtil.login(bizAccountDTO.getId());
        return Result.success(StpUtil.getTokenValue());
        // Login success logic here
    }


    @PostMapping("/logout")
    public Result logout() {
        StpUtil.logout();
        return Result.success("注销登录成功");
    }


}
